/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.carcophan.jimdb.jsf.backing;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import nl.captcha.Captcha;
import nl.captcha.backgrounds.BackgroundProducer;
import nl.captcha.backgrounds.FlatColorBackgroundProducer;
import nl.captcha.gimpy.DropShadowGimpyRenderer;
import nl.captcha.text.producer.DefaultTextProducer;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author joachim
 */
@Named(value = "captchaBackingBean")
@SessionScoped
public class CaptchaBackingBean implements Serializable {

    private Captcha captcha;

    public Captcha getCaptcha() {
        return captcha;
    }

    public void setCaptcha(Captcha captcha) {
        this.captcha = captcha;
    }

    /** Creates a new instance of CaptchaBackingBean */
    public CaptchaBackingBean() {
    }

    public StreamedContent getNewCaptcha() throws IOException {
        this.captcha = new Captcha.Builder(150, 50).addBackground(new FlatColorBackgroundProducer(Color.WHITE)).addText().gimp().gimp(new DropShadowGimpyRenderer()).addNoise().build();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
        encoder.encode(captcha.getImage());
        byte[] fileData = baos.toByteArray();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileData);
        StreamedContent myImage = new DefaultStreamedContent(byteArrayInputStream, "image/jpeg");
        return myImage;
    }
}
